package com.tzinfo.tzb;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.Image;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.tzinfo.data.SubjectResult;
import com.tzinfo.data.SubjectResultData;
import com.tzinfo.data.TztData;
import com.tzinfo.tzb.view.adapter.SubjecttAdapter;
import com.tzinfo.tzt.R;
import com.tzinfo.tzt.util.HttpUtils;
import com.tzinfo.tzt.util.ResultMessage_NoData;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2014/11/22.
 */

//应该还需要加入三个按钮，未审核，已删除，正常
public class SubjectListActivity extends Activity implements SubjecttAdapter.SubjectInterface {
    private int fid;
    private int displayorder = 0;
    private TextView tv_title;
    private TextView tv_notpass;
    private TextView tv_pass;
    private TextView tv_deleted;
    private TextView tv_search;
    private EditText et_search;
    private PullToRefreshListView listView;
    private ImageView iv_search_del;
    int pagesize = 10;
    private boolean isLoadingData = false;
    int page = 1;
    private int i;//用户接受指定的删除position
    boolean b = false;//改变布局,为假是隐藏
    List<SubjectResultData> listData;
    private SubjecttAdapter adapter;
    ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_subject_list);
        tv_title = (TextView) findViewById(R.id.subject_title);
        tv_notpass = (TextView) findViewById(R.id.subject_notpass);
        tv_pass = (TextView) findViewById(R.id.subject_pass);
        tv_deleted = (TextView) findViewById(R.id.subject_deleted);
        tv_search = (TextView) findViewById(R.id.subject_search);

        iv_search_del = (ImageView) findViewById(R.id.subject_iv_search);
        et_search = (EditText) findViewById(R.id.subject_et_search);

        tv_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv_title.setVisibility(View.GONE);
                et_search.setVisibility(View.VISIBLE);
                tv_search.setVisibility(View.GONE);
                iv_search_del.setVisibility(View.VISIBLE);
            }
        });

        iv_search_del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv_title.setVisibility(View.VISIBLE);
                et_search.setVisibility(View.GONE);
                tv_search.setVisibility(View.VISIBLE);
                iv_search_del.setVisibility(View.GONE);
            }
        });

        et_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    page--;
                    new SearchTask().execute(et_search.getText().toString());
                }
                tv_title.setVisibility(View.VISIBLE);
                tv_search.setVisibility(View.VISIBLE);
                et_search.setVisibility(View.GONE);
                iv_search_del.setVisibility(View.GONE);
                return false;
            }
        });
        tv_pass.setSelected(true);


        progressDialog = new ProgressDialog(SubjectListActivity.this);
        // progressDialog.setMessage("载入中");
        progressDialog.setCancelable(false);


        Intent intent = getIntent();
        fid = intent.getExtras().getInt("fid");
        tv_title.setText(intent.getExtras().getString("name"));
        listView = (PullToRefreshListView) findViewById(R.id.subject_listView);
        listView.setMode(PullToRefreshBase.Mode.BOTH);

        ILoadingLayout endLabels = listView.getLoadingLayoutProxy(false, true);
        endLabels.setPullLabel("上拉加载更多");
        endLabels.setReleaseLabel("松开加载");
        endLabels.setRefreshingLabel("正在加载");
        new GetDataTask().execute();

        tv_notpass.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!tv_notpass.isSelected()) {
                    displayorder = -2;
                    page = 1;
                    tv_notpass.setSelected(true);
                    tv_pass.setSelected(false);
                    tv_deleted.setSelected(false);
                    b = true;
                    new GetDataTask().execute();
                }
            }
        });
        tv_pass.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!tv_pass.isSelected()) {
                    displayorder = 0;
                    page = 1;
                    tv_notpass.setSelected(false);
                    tv_pass.setSelected(true);
                    tv_deleted.setSelected(false);
                    b = false;
                    new GetDataTask().execute();
                }
            }
        });
        tv_deleted.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!tv_deleted.isSelected()) {
                    displayorder = -1;
                    page = 1;
                    tv_notpass.setSelected(false);
                    tv_pass.setSelected(false);
                    tv_deleted.setSelected(true);
                    b = false;
                    new GetDataTask().execute();
                }
            }
        });


        listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                String label = DateUtils.formatDateTime(
                        SubjectListActivity.this,
                        System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME
                                | DateUtils.FORMAT_SHOW_DATE
                                | DateUtils.FORMAT_ABBREV_ALL);


                if (!isLoadingData) {
                    page = 1;
                    refreshView.getLoadingLayoutProxy()
                            .setLastUpdatedLabel(label);
                    new GetDataTask().execute();
                }

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                String label = DateUtils.formatDateTime(
                        SubjectListActivity.this,
                        System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME
                                | DateUtils.FORMAT_SHOW_DATE
                                | DateUtils.FORMAT_ABBREV_ALL);
                // 显示最后更新的时间
                if (!isLoadingData) {
                    refreshView.getLoadingLayoutProxy()
                            .setLastUpdatedLabel(label);
                    new GetDataTask().execute();
                }
            }
        });


    }

    @Override
    public void delete(int a, int b, String s, int position) {
        DelTask t = new DelTask();
        i = position;
        t.execute(String.valueOf(a), String.valueOf(b), s);
    }

    @Override
    public void pass(int a, int b, String s, int position) {
        DelTask t = new DelTask();
        i = position;
        t.execute(String.valueOf(a), String.valueOf(b), s);
    }

    @Override
    public void digest(int a, int b, int type) {
        DigestTask digestTask = new DigestTask();
        digestTask.execute(String.valueOf(a), String.valueOf(b), String.valueOf(type));
    }


    public class DigestTask extends AsyncTask<String, Void, ResultMessage_NoData> {

        @Override
        protected ResultMessage_NoData doInBackground(String... params) {
            List<NameValuePair> pairs = new ArrayList<NameValuePair>();
            pairs.add(new BasicNameValuePair("Fid", params[0]));
            pairs.add(new BasicNameValuePair("Tid", params[1]));
            pairs.add(new BasicNameValuePair("Type", params[2]));//精华等级
            pairs.add(new BasicNameValuePair("sessionid", TztData.userInfo.getData().getSessionID()));
            String GetDataUrl = "http://tzt.tzinfo.net/mob/api/ForumDigest.ashx";
            String DataString = HttpUtils.doPostMethod(GetDataUrl, pairs);
            Gson gson = new Gson();
            ResultMessage_NoData result = gson.fromJson(DataString, ResultMessage_NoData.class);
            return result;
        }

        @Override
        protected void onPostExecute(ResultMessage_NoData resultMessage_noData) {
            super.onPostExecute(resultMessage_noData);
            if (resultMessage_noData.getSuccess()) {
                Toast.makeText(SubjectListActivity.this, resultMessage_noData.getErrorMsg(), Toast.LENGTH_SHORT).show();
            }
        }
    }

    public class DelTask extends AsyncTask<String, Void, ResultMessage_NoData> {

        @Override
        protected ResultMessage_NoData doInBackground(String... params) {
            List<NameValuePair> pairs = new ArrayList<NameValuePair>();
            pairs.add(new BasicNameValuePair("fid", params[0]));
            pairs.add(new BasicNameValuePair("Tid", params[1]));
            pairs.add(new BasicNameValuePair("type", params[2]));//Del:删除  Pass:审核  Close:关闭

            pairs.add(new BasicNameValuePair("sessionid", TztData.userInfo.getData().getSessionID()));
            String GetDataUrl = "http://tzt.tzinfo.net/mob/api/ForumThreadOp.ashx";
            String DataString = HttpUtils.doPostMethod(GetDataUrl, pairs);
            Gson gson = new Gson();
            ResultMessage_NoData result = gson.fromJson(DataString, ResultMessage_NoData.class);
            return result;
        }

        @Override
        protected void onPostExecute(ResultMessage_NoData resultMessage_noData) {
            super.onPostExecute(resultMessage_noData);
            if (resultMessage_noData.getSuccess()) {
                Toast.makeText(SubjectListActivity.this, resultMessage_noData.getErrorMsg(), Toast.LENGTH_SHORT).show();
                listData.remove(i);
                adapter.notifyDataSetChanged();
            }
        }
    }

    public class GetDataTask extends AsyncTask<String, Void, SubjectResult> {
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog.show();
            if (isLoadingData) {
                this.cancel(true);
                return;
            }
            isLoadingData = true;
        }

        @Override
        protected SubjectResult doInBackground(String... params) {
            List<NameValuePair> pairs = new ArrayList<NameValuePair>();
            pairs.add(new BasicNameValuePair("fid", String.valueOf(fid)));
            pairs.add(new BasicNameValuePair("displayorder", String.valueOf(displayorder)));
            pairs.add(new BasicNameValuePair("type", "0"));//0为管理员
            pairs.add(new BasicNameValuePair("Page", String.valueOf(page)));
            pairs.add(new BasicNameValuePair("Pagesize", String.valueOf(pagesize)));
            pairs.add(new BasicNameValuePair("sessionid", TztData.userInfo.getData().getSessionID()));
            String GetDataUrl = "http://tzt.tzinfo.net/mob/api/ForumthreadListM.ashx";
            String DataString = HttpUtils.doPostMethod(GetDataUrl, pairs);
            Gson gson = new Gson();
            SubjectResult result = gson.fromJson(DataString, SubjectResult.class);
            return result;
        }

        @Override
        protected void onPostExecute(SubjectResult result) {
            super.onPostExecute(result);
            if (result.getData().size() > 0) {
                if (adapter == null || page == 1) {
                    listData = result.getData();
                } else {
                    listData.addAll(result.getData());
                }
                if (listData.size() <= pagesize) {
                    adapter = new SubjecttAdapter(SubjectListActivity.this, listData, b);
                    listView.setAdapter(adapter);
                }

                page++;
                adapter.notifyDataSetChanged();
                listView.onRefreshComplete();
                isLoadingData = false;

            } else {
                Toast.makeText(SubjectListActivity.this, "没有数据", Toast.LENGTH_SHORT)
                        .show();
                listView.onRefreshComplete();
                isLoadingData = false;
            }
            progressDialog.dismiss();
        }
    }

    public class SearchTask extends AsyncTask<String, Void, SubjectResult> {
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog.show();
            if (isLoadingData) {
                this.cancel(true);
                return;
            }
            isLoadingData = true;
        }

        @Override
        protected SubjectResult doInBackground(String... params) {
            List<NameValuePair> pairs = new ArrayList<NameValuePair>();
            pairs.add(new BasicNameValuePair("fid", String.valueOf(fid)));
            pairs.add(new BasicNameValuePair("displayorder", String.valueOf(displayorder)));
            pairs.add(new BasicNameValuePair("type", "0"));//0为管理员
            pairs.add(new BasicNameValuePair("skey", params[0]));
            pairs.add(new BasicNameValuePair("Page", String.valueOf(page)));
            pairs.add(new BasicNameValuePair("Pagesize", String.valueOf(pagesize)));
            pairs.add(new BasicNameValuePair("sessionid", TztData.userInfo.getData().getSessionID()));
            String GetDataUrl = "http://tzt.tzinfo.net/mob/api/ForumthreadListM.ashx";
            String DataString = HttpUtils.doPostMethod(GetDataUrl, pairs);
            Gson gson = new Gson();
            SubjectResult result = gson.fromJson(DataString, SubjectResult.class);
            return result;
        }

        @Override
        protected void onPostExecute(SubjectResult result) {
            super.onPostExecute(result);
            if (result.getData().size() > 0) {
                if (adapter == null || page == 1) {
                    listData = result.getData();
                } else {
                    listData.addAll(result.getData());
                }
                if (listData.size() <= pagesize) {
                    adapter = new SubjecttAdapter(SubjectListActivity.this, listData, b);
                    listView.setAdapter(adapter);
                }

                page++;
                adapter.notifyDataSetChanged();
                listView.onRefreshComplete();
                isLoadingData = false;

            } else {
                Toast.makeText(SubjectListActivity.this, "没有数据", Toast.LENGTH_SHORT)
                        .show();
                listView.onRefreshComplete();
                isLoadingData = false;
            }
            progressDialog.dismiss();
        }
    }

    public void goback(View view) {
        this.finish();
    }


}
